import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/pages/home/home/model/device_list_resp.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

/// 切换设备 页面
class UnbindDevicePage extends ConsumerStatefulWidget {
  const UnbindDevicePage({super.key});

  @override
  ConsumerState<UnbindDevicePage> createState() => _UnbindDevicePageState();
}

class _UnbindDevicePageState extends ConsumerState<UnbindDevicePage> {
  bool showLoading = true;
  int pageNum = 1;
  List<DeviceListData> deviceList = <DeviceListData>[];
  late EasyRefreshController _refreshController;

  _buildLoading() {
    return Center(
      child: CircularProgressIndicator(
        color: AppTheme.themeConfig.primaryColor,
      ),
    );
  }

  _buildList() {
    return ListView.builder(
      itemCount: deviceList.length,
      itemBuilder: (context, index) {
        return _buildCell(index);
      },
    );
  }

  _buildCell(int index) {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    DeviceListData device = deviceList[index];
    // 设备信息cell
    return _UnbindDeviceTile(
      name: device.deviceName ?? '',
      imei: device.imei ?? '',
      onUnbind: () {
        showDialog(
          context: context,
          builder: (context) {
            return CupertinoAlertDialog(
              title: const Text('提示'),
              content: const Text('确定要解绑该设备吗？'),
              actions: [
                TextButton(onPressed: () { context.pop(); }, child: const Text('取消')),
                TextButton(onPressed: () { _unbindDevice(device.imei!); }, child: const Text('确定', style: TextStyle(color: Colors.red))),
              ],
            );
          },
        );
      },
    );
  }

  _unbindDevice(String imei) async {
    final isCurrentDevice = ref.read(deviceInfoProvider).imei == imei;
    final postData = {
      'imei': imei,
    };
    ToastUtils.showLoading();
    final res = await post<BaseResp, BaseResp>('/device/unbind', data: postData, decodeType: BaseResp());
    res.when(success: (BaseResp resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 从列表中移除设备
        deviceList.removeWhere((element) => element.imei == imei);
        ToastUtils.showToast('解绑成功');
        context.pop();
        if (isCurrentDevice) {
          ref.read(deviceInfoProvider.notifier).switchCurrentDevice(() {});
        }
      } else {
        ToastUtils.showToast(resp.msg ?? '解绑失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('解绑失败 code: $code msg: $msg');
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 在build完成后回调
      // 获取设备列表
      _fetchDeviceList(true);
    });
    super.initState();
    _refreshController = EasyRefreshController(
      controlFinishLoad: true,
      controlFinishRefresh: true,
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  _fetchDeviceList(bool isRefresh) async {
    final queryParams = {
      'pageNum': pageNum,
      'pageSize': 10,
    };
    final res = await get<DeviceListResp, DeviceListResp>('/device/list',
        queryParameters: queryParams, decodeType: DeviceListResp());
    res.when(success: (DeviceListResp resp) {
      if (resp.code == 200) {
        if (isRefresh) {
          deviceList.clear();
          deviceList.addAll(resp.data!);
          // 判断是否还有更多数据
          if (resp.data == null || resp.data!.isEmpty || resp.data!.length < 10) {
            _refreshController.finishLoad(IndicatorResult.noMore);
          } else {
            _refreshController.finishRefresh();
          }
          pageNum++;
        } else {
          if (resp.data == null || resp.data!.isEmpty) {
            _refreshController.finishLoad(IndicatorResult.noMore);
          } else {
            pageNum++;
            deviceList.addAll(resp.data!);
            _refreshController.finishLoad();
          }
        }
      } else {
        ToastUtils.showToast(resp.msg ?? '获取设备列表失败');
      }
      setState(() {
        showLoading = false;
      });
    }, failure: (String msg, int code) {
      XLogger.error('获取设备列表失败 code: $code msg: $msg');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '解绑设备',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      backgroundColor: ColorUtils.hexToColor('#f5f5f5'),
      body: EasyRefresh(
        controller: _refreshController,
        onRefresh: () async {
          pageNum = 1;
          await _fetchDeviceList(true);
          _refreshController.finishRefresh();
        },
        onLoad: () async {
          await _fetchDeviceList(false);
        },
        child: showLoading ? _buildLoading() : _buildList(),
      ),
    );
  }
}

class _UnbindDeviceTile extends StatelessWidget {
  final String name;
  final String imei;
  final VoidCallback onUnbind;
  const _UnbindDeviceTile({required this.name, required this.imei, required this.onUnbind});

  @override
  Widget build(BuildContext context) {
    return Stack(children: [
      Container(
        height: 60,
        margin: const EdgeInsets.only(left: 20, right: 20, top: 20),
        padding: const EdgeInsets.only(left: 20, right: 20),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8)),
        child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Expanded(
            child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
              Text(name, style: const TextStyle(fontSize: 16), maxLines: 1, overflow: TextOverflow.ellipsis),
              const SizedBox(width: 10),
              Text('设备号：${imei}', style: const TextStyle(fontSize: 14)),
            ]),
          ),
          GestureDetector(
            onTap: onUnbind,
            child: Container(
              padding: const EdgeInsets.only(left: 10, right: 10, top: 2, bottom: 2),
              decoration: BoxDecoration(color: ColorUtils.hexToColor('#fa3534'), borderRadius: BorderRadius.circular(8)),
              child: const Text('解绑', style: TextStyle(color: Colors.white, fontSize: 12)),
            ),
          ),
        ]),
      ),
    ]);
  }
}
